package com.kqb.order.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.kqb.api.product.dto.OrderItemDTO;
import com.kqb.api.product.feign.SkuFeignClient;
import com.kqb.api.product.feign.SpuFeignClient;
import com.kqb.api.product.vo.SkuVO;
import com.kqb.api.product.vo.SpuVO;
import com.kqb.api.user.vo.UserAddrVO;
import com.kqb.api.user.feign.UserAddrFeignClient;
import com.kqb.common.core.utils.AjaxResult;
import com.kqb.common.redis.utils.RedisUtils;
import com.kqb.common.security.AuthUserContext;
import com.kqb.order.dto.OrderDTO;
import com.kqb.order.service.IOrderService;
import com.kqb.order.vo.ShopCartItemVO;
import com.kqb.order.vo.ShopCartOrderMergerVO;
import com.kqb.order.vo.ShopCartOrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单信息 前端控制器
 * </p>
 *
 * @author 杉果树皮
 * @since 2025-04-12
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单")
public class OrderController {

//    @Autowired
//    UserAddrFeignClient userAddrFeignClient;

//    @Autowired
//    SkuFeignClient skuFeignClient;

//    @Autowired
//    SpuFeignClient spuFeignClient;

    @Autowired
    RedisUtils redisUtils;


    @Autowired
    IOrderService iOrderService;

    /**
     * 提交商品将订单信息返回给前端
     */
    @PostMapping("/confirm")
    @ApiOperation("商品提交")
    public AjaxResult confirm(@RequestBody OrderDTO orderDTO) {

        // 返回给前端的订单信息
        ShopCartOrderMergerVO shopCartOrderMergerVO = new ShopCartOrderMergerVO();
        // 1. 获取用户id
        Long userId = AuthUserContext.get().getUserId();

        // 2. 获取用户地址信息
//        UserAddrVO userAddrVO = userAddrFeignClient.getAddrByUserIdAddrId(userId, orderDto.getAddrId());
        //模拟用户地址数据
        UserAddrVO userAddrVO = new UserAddrVO()
                .setMobile("13800138000")
                .setIsDefault(1)
                .setConsignee("张三")
                .setProvinceId(110000L)
                .setProvince("北京市")
                .setCityId(110100L)
                .setCity("北京市")
                .setAreaId(110105L)
                .setArea("朝阳区")
                .setPostCode("100020")
                .setAddr("朝阳区XX街道XX号院XX号楼XX单元XX室")
                .setLng(116.407526)
                .setLat(39.904030)
                .setAddrId(123456789012345678L);

        shopCartOrderMergerVO.setUserAddr(userAddrVO);
        shopCartOrderMergerVO.setDvyType(orderDTO.getDvyType());


        // 3. 获取商品详细信息
        //判断是不是直接购买的
        ArrayList<OrderItemDTO> orderItems = new ArrayList<>();
        if (orderDTO.getIsCart() == 1) {
            orderItems = CollectionUtil.toList(orderDTO.getOrderItemDto());
        } else {
            //从购物车服务获取商品信息
            for (int i = 1; i <= 3; i++) {
                OrderItemDTO orderItemDTO = new OrderItemDTO();
                orderItemDTO.setSpuId((long) i);
                orderItemDTO.setSkuId((long) (i + 1));
                orderItemDTO.setProdCount(6 + i);
                orderItemDTO.setShopId((long) i);
                orderItems.add(orderItemDTO);
            }

        }


        List<ShopCartOrderVO> shopCartOrders = assembleShopCartOrder(orderItems, userId);
        List<ShopCartItemVO> filterShopItems = new ArrayList<>();
        shopCartOrders.forEach(el -> {
            List<ShopCartItemVO> shopCartItemVO = el.getShopCartItemVO();
            if (null != shopCartItemVO) {
                filterShopItems.addAll(shopCartItemVO);
            }
        });
        shopCartOrderMergerVO.setShopCartOrders(shopCartOrders);
        shopCartOrderMergerVO.setFilterShopItems(filterShopItems);

        //将组装好的订单信息存入redis

        // 1. 防止重复提交
        Boolean exists = redisUtils.exists("confirm:order:" + userId);
        if (exists) {
            return AjaxResult.error("请不要重复提交");
        }

        // 2. 将订单信息存入缓存
        redisUtils.setJson("confirm:order:" + userId, shopCartOrderMergerVO, 60 * 15);

        return AjaxResult.success(shopCartOrderMergerVO);
    }

    @PostMapping("/submit")
    @ApiOperation("提交订单并返回订单号")
    public AjaxResult submit() {
        Long userId = AuthUserContext.get().getUserId();

        // 1. 判断订单是否过期
        Boolean exists = redisUtils.exists("confirm:order:" + userId);
        if (!exists) {
            return AjaxResult.error("订单已过期");
        }
        // 2. 获取订单信息
        ShopCartOrderMergerVO shopCartOrderMerger = redisUtils.getJson("confirm:order:" + userId, new TypeReference<ShopCartOrderMergerVO>() {
        });

        List<Long> orderIds = iOrderService.submit(userId, shopCartOrderMerger);
        redisUtils.del("confirm:order:" + userId);
        return AjaxResult.success(orderIds);
    }


    //获取购物车商品列表
    public ShopCartItemVO getShopCartItems(OrderItemDTO orderItem, long userId) {
        //        SkuVO skuVO = skuFeignClient.getBySkuId(orderItem.getSkuId());
//        SpuVO spuVO = spuFeignClient.getBySpuId(orderItem.getSpuId());

        //模拟数据
        SpuVO spuVO = new SpuVO()
                .setSpuId(100001L)
                .setBrandId(5001L)
                .setShopCategoryId(3000101L)
                .setShopId(80001L)
                .setName("苹果 iPhone 15 Pro")
                .setSellingPoint("A17 Pro 芯片，钛金属边框，超视网膜 XDR 显示屏")
                .setMainImgUrl("https://img.example.com/apple_iphone15_pro_main.jpg")
                .setImgUrls("https://img.example.com/apple_iphone15_pro_1.jpg,https://img.example.com/apple_iphone15_pro_2.jpg")
                .setPriceFee(999900L)
                .setMarketPriceFee(1099900L)
                .setCategoryId(30001L);
        SkuVO skuVO = new SkuVO()
                .setSpuId(100001L)
                .setSkuName("Apple iPhone 15 Pro 128GB 黑色")
                .setAttrs("1,3,5")
                .setPriceFee(999900L)
                .setMarketPriceFee(1099900L)
                .setPartyCode("IPH15PB128")
                .setModelId("IPH15PB128MOD")
                .setWeight(new BigDecimal("0.220"))
                .setVolume(new BigDecimal("0.008"))
                .setImgUrl("https://img.example.com/apple_iphone15_pro_black_128gb.jpg")
                .setSkuId(10000101L);

        //生成店铺订单商品列表
        ShopCartItemVO shopCartItemVO = new ShopCartItemVO();
        shopCartItemVO.setShopId(orderItem.getShopId());
        shopCartItemVO.setSpuId(spuVO.getSpuId());
        shopCartItemVO.setSkuId(skuVO.getSkuId());
        shopCartItemVO.setUserId(userId);

        shopCartItemVO.setCount(orderItem.getProdCount());
        shopCartItemVO.setSkuPriceFee(skuVO.getPriceFee());
        shopCartItemVO.setTotalPrice(orderItem.getProdCount() * skuVO.getPriceFee());
        shopCartItemVO.setWeight(skuVO.getWeight());
        shopCartItemVO.setVolume(skuVO.getVolume());
        shopCartItemVO.setImgUrl(skuVO.getImgUrl());
        shopCartItemVO.setTotalAmount(orderItem.getProdCount() * skuVO.getPriceFee());
        shopCartItemVO.setSkuName(skuVO.getSkuName());
        shopCartItemVO.setSpuName(spuVO.getName());
        return shopCartItemVO;

    }


    //组装购物车订单
    public List<ShopCartOrderVO> assembleShopCartOrder(List<OrderItemDTO> orderItems, Long userId) {
        //根据店铺id将订单分类
        Map<Long, List<OrderItemDTO>> collect = orderItems.stream()
                .collect(Collectors.groupingBy(OrderItemDTO::getShopId));

        ArrayList<ShopCartOrderVO> shopCartOrders = new ArrayList<>();
        collect.forEach((k, v) -> {

            ArrayList<ShopCartItemVO> shopCartItems = new ArrayList<>();
            v.forEach(e -> {
                ShopCartItemVO shopCartItem = getShopCartItems(e, userId);
                shopCartItems.add(shopCartItem);
            });
            ShopCartOrderVO shopCartOrderVO = new ShopCartOrderVO();
            shopCartOrderVO.setShopId(k);
            //根据shopId 查询 店铺名称
            // TODO: 2025/4/16 调用用户服务得到店铺名称
            shopCartOrderVO.setShopName("店铺111");
            Map<String, Object> compute = compute(shopCartItems);
            shopCartOrderVO.setShopCartItemVO(shopCartItems);
            shopCartOrderVO.setTotal((Long) compute.get("total"));
            shopCartOrderVO.setTotalCount((Integer) compute.get("totalCount"));
            shopCartOrders.add(shopCartOrderVO);
        });
        return shopCartOrders;
    }

    //计算订单总价 和总数
    public Map<String, Object> compute(List<ShopCartItemVO> shopCartItems) {

        //订单总价
        Long total = 0L;
        //商品总数
        Integer totalCount = 0;
        for (ShopCartItemVO shopCartItem : shopCartItems) {
            total += shopCartItem.getSkuPriceFee();
            totalCount += shopCartItem.getCount();
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("totalCount", totalCount);
        return map;
    }

}
